package com.demo.xmtx.service;

import com.demo.xmtx.entity.Inventory;
import com.demo.xmtx.entity.Order;
import com.demo.xmtx.mapper.InventoryMapper;
import com.demo.xmtx.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService {

  @Autowired
  private OrderMapper orderMapper;

  @Autowired
  private InventoryMapper inventoryMapper;

  @Transactional
  public Order createOrder(Long userId, Long productId, Integer quantity) {
    // 检查库存
    Inventory inventory = inventoryMapper.selectInventoryByProductId(productId);
    if (inventory == null || inventory.getStock() < quantity) {
      throw new RuntimeException("库存不足");
    }

    // 扣减库存（使用乐观锁）
    inventory.setStock(inventory.getStock() - quantity);
    int rows = inventoryMapper.updateInventoryWithVersion(inventory);
    if (rows == 0) {
      throw new RuntimeException("库存更新失败，请重试");
    }

    // 创建订单
    Order order = new Order();
    order.setUserId(userId);
    order.setProductId(productId);
    order.setQuantity(quantity);
    order.setStatus("CREATED");
    orderMapper.insertOrder(order);

    return order;
  }

  @Transactional
  public void purchaseOrder(Long orderId) {
    // 查询订单
    Order order = orderMapper.selectOrderById(orderId);
    if (order == null) {
      throw new RuntimeException("订单不存在");
    }

    // 检查订单状态是否为“CREATED”
    if (!"CREATED".equals(order.getStatus())) {
      throw new RuntimeException("订单状态不允许更新");
    }

    // 查询库存
    Inventory inventory = inventoryMapper.selectInventoryByProductId(order.getProductId());
    if (inventory == null || inventory.getStock() < order.getQuantity()) {
      throw new RuntimeException("库存不足");
    }

    // 扣减库存（使用乐观锁）
    inventory.setStock(inventory.getStock() - order.getQuantity());
    int rows = inventoryMapper.updateInventoryWithVersion(inventory);
    if (rows == 0) {
      throw new RuntimeException("库存更新失败，请重试");
    }

    // 更新订单状态为“PURCHASED”
    orderMapper.updateOrderStatus(orderId, "PURCHASED");
  }

  public Order getOrderById(Long id) {
    return orderMapper.selectOrderById(id);
  }

  public void deleteOrderById(Long id) {
    orderMapper.deleteOrderById(id);
  }

  public void updateOrderStatus(Long id, String status) {
    orderMapper.updateOrderStatus(id, status);
  }
}
